import {
  IconComponentPlaceholderStroked,
  IconLock,
  IconLockStroked,
  IconScissors,
  IconSetting,
  IconUnlock,
  IconUnlockStroked,
  IconUser,
  IconUserSetting,
  IconWrench,
} from '@douyinfe/semi-icons';
import { Button, Layout, Nav } from '@douyinfe/semi-ui';
import MainRoutes from './main-routes';
import './main-layouts.scss';
import cns from 'classnames';
import { useLocation, useNavigate } from 'react-router-dom';
import TemplateBreadcrumb from './breadcrumb/template-breadcrumb';
import MainProvider, { NavStatus, useMainContext } from './main-context';
import { useIgnoreKeepAlive } from 'react-fiber-keep-alive';
import { useEffect, useMemo, useState } from 'react';

const MainTemplate = () => {
  // const navigation = useNavigation();

  const ignoreCache = useIgnoreKeepAlive();

  // useEffect(() => {
  //   if (!['/main/domain/menu'].includes(location.pathname)) {
  //     ignoreCache('ka-domain');
  //   }
  // }, [location]);

  return (
    <MainProvider>
      <Layout className='bg-gray-100 overflow-y-hidden'>
        <MainSider />
        <MainLayout />
      </Layout>
    </MainProvider>
  );
};

const MainSider = () => {
  const { Sider } = Layout;
  const navigate = useNavigate();
  const location = useLocation();

  const menus: any = {
    system: [
      {
        itemKey: 'platform',
        icon: <IconComponentPlaceholderStroked />,
        text: '平台基础',
        items: [
          {
            itemKey: 'coordination',
            text: '协同总览',
            onClick: () => {
              navigate('coordination');
            },
          },
          {
            itemKey: 'integral',
            text: '积分总览',
            onClick: () => {
              navigate('integral');
            },
          },
          // {
          //   itemKey: 'contact',
          //   text: '协同通讯录',
          //   onClick: () => {
          //     navigate('contact');
          //   },
          // },
          // {
          //   itemKey: 'organize',
          //   text: '组织管理',
          //   onClick: () => {
          //     navigate('organize');
          //   },
          // },
          // {
          //   itemKey: 'application',
          //   text: '应用管理',
          //   onClick: () => {
          //     navigate('application');
          //   },
          // },
        ],
      },
      {
        itemKey: 'basic',
        icon: <IconUser />,
        text: '基础配置',
        items: [
          {
            itemKey: 'user',
            text: '用户管理',
            onClick: () => {
              navigate('user');
            },
          },
          // {
          //   itemKey: 'department',
          //   text: '部门管理',
          //   onClick: () => {
          //     navigate('department');
          //   },
          // },
          // {
          //   itemKey: 'role',
          //   text: '角色管理',
          //   onClick: () => {
          //     navigate('role');
          //   },
          // },
          {
            itemKey: 'dictionary',
            text: '字典管理',
            onClick: () => {
              navigate('dictionary');
            },
          },
          // {
          //   itemKey: 'position',
          //   text: '岗位管理',
          //   disabled: true,
          // },
        ],
      },
    ],
    // config: [
    //   {
    //     itemKey: 'feedback',
    //     icon: <IconWrench />,
    //     text: '平台运维',
    //     items: [
    //       {
    //         itemKey: 'feedback_page',
    //         text: '反馈管理',
    //         onClick: () => {
    //           navigate('feedback');
    //         },
    //       },
    //     ],
    //   },
    // ],
  };

  const MainContext = useMainContext();
  const MainAction = useMemo(() => {
    return {
      locking: MainContext.locking,
      setLocking: MainContext.setLocking,
    };
  }, [MainContext]);

  const [menuCategory, setMenuCategory] = useState('system');

  useEffect(() => {
    const floatnav = document.querySelector('.float-nav');
    const onmouseleave = (e: any) => {
      MainAction.setLocking(NavStatus.hide);
    };
    if (floatnav && MainAction.locking == NavStatus.show) {
      floatnav.addEventListener('mouseleave', onmouseleave, false);
    }
    return () => {
      if (floatnav) {
        floatnav.removeEventListener('mouseleave', onmouseleave);
      }
    };
  }, [MainAction.locking]);

  const selectedKeys = useMemo(() => {
    let allMenus: any[] = [];
    Object.values(menus).forEach((_menu: any) => {
      _menu.forEach((item: any) => {
        allMenus = [...allMenus, ...item.items];
      });
    });

    console.log(' allMenus', Object.values(menus), allMenus);

    const menu = allMenus.find((roleKey: any) => {
      return (
        location.pathname.includes(roleKey.itemKey) &&
        roleKey.itemKey?.length > 0
      );
    });
    if (menu) {
      return [menu.itemKey];
    }
    return [];

    return [];
  }, [location]);

  console.log('selectedKeys', selectedKeys);

  return (
    <Sider>
      <div className='flex h-full'>
        <Nav
          isCollapsed
          className='h-full'
          items={[
            {
              itemKey: 'system',
              icon: <IconUserSetting />,
              text: '用户设置',
              onClick: () => {
                setMenuCategory('system');
                if (MainAction.locking == NavStatus.hide) {
                  MainAction.setLocking(NavStatus.show);
                }
              },
            },
            // {
            //   itemKey: 'config',
            //   icon: <IconSetting />,
            //   text: '运维设置',
            //   onClick: () => {
            //     setMenuCategory('config');
            //     if (MainAction.locking == NavStatus.hide) {
            //       MainAction.setLocking(NavStatus.show);
            //     }
            //   },
            // },
          ]}
        />
        {(MainAction.locking == NavStatus.lock ||
          MainAction.locking == NavStatus.show) && (
          <Nav
            className={cns('h-full float-nav inline-flex', {
              'absolute top-0 start-[60px] z-[1000]':
                MainAction.locking == NavStatus.show,
            })}
            defaultOpenKeys={['platform', 'basic', 'feedback']}
            selectedKeys={selectedKeys}
            items={menus[menuCategory]}
          >
            {(MainAction.locking == NavStatus.show ||
              MainAction.locking == NavStatus.lock) && (
              <div className='absolute bottom-0 end-0 p-2'>
                <Button
                  icon={
                    MainAction.locking == NavStatus.lock ? (
                      <IconLock />
                    ) : (
                      <IconUnlock />
                    )
                  }
                  type='tertiary'
                  onClick={() =>
                    MainAction.setLocking(
                      MainAction.locking == NavStatus.lock
                        ? NavStatus.show
                        : NavStatus.lock
                    )
                  }
                ></Button>
              </div>
            )}
          </Nav>
        )}
      </div>
    </Sider>
  );
};

const MainLayout = () => {
  const MainContext = useMainContext();
  const MainAction = useMemo(() => {
    return {
      loading: MainContext.loading,
    };
  }, [MainContext]);

  return (
    <div className='relative flex-auto'>
      <div
        className='relative w-full h-full flex flex-col'
        style={{
          overflowY: MainAction.loading === 'loading' ? 'hidden' : 'auto',
        }}
      >
        <div className='p-5 pt-10 pb-0 flex-1'>
          <div className='flex align-center sticky top-0 z-[998] bg-gray-100/75 -mx-5 px-5 -mt-10 h-10 lh-10'>
            <TemplateBreadcrumb />
          </div>
          <MainRoutes />
        </div>
        <div className='p-5 text-sm text-gray-500 flex-none'>
          &copy; 2023 Corp. All rights reserved. Designed & Developed with love
          by Sedt-ft
        </div>
      </div>
      <div
        className={cns('transition-mask', {
          active: MainAction.loading,
        })}
      ></div>
    </div>
  );
};

export default MainTemplate;
